import {createSlice, createAsyncThunk} from '@reduxjs/toolkit'
import {UserStore} from '../ts/slice/user'
import {getUser} from '@request/user'



export const useSliceName = "UserSlice"
const initUserState:UserStore = {
  user: [],
  count: 1,
}
/* 获取用户数据 */
export const getUserData = createAsyncThunk(
  useSliceName+'/getUserDataThunk',
  async (payload) => {
    try {
      const userData = await getUser({url: "http://localhost:3535/user/getUser"}).then(data => data.json())
      return userData
    } catch (error) {
     throw new Error('slice user userData error') 
    }
  }
)


export const userSlice = createSlice({
  name: useSliceName,
  initialState: initUserState,
  reducers: {
    addCount(state, {payload}) {
      state.count += payload
    },
    reduceCount(state, {payload}) {
      state.count -= payload
    }
  },
  extraReducers: (builder) => {
    // 成功
    builder.addCase(getUserData.fulfilled, (state, {payload}) => {
      return {
        ...state,
        user: payload.data
      }
    })
    // 错误
    builder.addCase(getUserData.rejected, (state, action) => {
      const isProd = process.env.NODE_ENV === 'production'
      throw isProd ? new Error('slice getUserData error') : 'slice getUserData error'
    })
  }
})

export const  {
  addCount,
  reduceCount
} = userSlice.actions
export default userSlice.reducer